import { activeTabs, addTabs, removeTabs } from '@/store/modules/tabs'
import { useAppDispatch, useAppSelector } from '@/store/hooks'
import { useCallback, useEffect } from 'react'

import { Tabs } from 'antd'
import { setSelectedKeys } from '@/store/modules/front'
import { useLocation } from 'react-router-dom'
import { useNavigate } from 'react-router-dom'

export default function TabsViews() {
  // 获取当前页面的路径
  const location = useLocation()
  // 获取仓库的数据
  const { tags, activeTagId } = useAppSelector((a) => a.tabs)
  const { definedLocale, Menus } = useAppSelector((a) => a.front)

  // 获取dispatch函数
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  //切换面板的回调
  const onChange = (change: any) => {
    if (change == '') {
      navigate('/')
      dispatch(activeTabs(''))
      dispatch(setSelectedKeys(''))
      return false
    } else {
      // 获取链接
      const tag = tags.find((tag) => tag.key === change)

      if (tag) {
        setCurrentTag(tag.key)
      }
    }
  }

  // 设置当前标签的回调函数,设置当前的点击标签
  const setCurrentTag = useCallback(
    (id?: string) => {
      const tag = tags.find((item) => {
        if (id) {
          return item.key === id
        } else {
          return item.key === location.pathname
        }
      })
      if (tag) {
        dispatch(setSelectedKeys(tag.key))
        dispatch(activeTabs(tag.key))
        navigate(tag.key)
      }
    },
    [dispatch, location.pathname, navigate, tags]
  )

  // 关闭标签时的回调函数
  const onClose = (targetKey: string) => {
    dispatch(removeTabs(targetKey))
  }

  // 在组件挂载时添加标签
  useEffect(() => {
    if (Menus.length) {
      let menu = {}
      Menus.some((e) => {
        if (e.children) {
          menu = e.children.find((ele) => '/' + ele.key === location.pathname)
          return menu // 返回 true 停止遍历循环
        }
      })

      if (menu) {
        dispatch(
          addTabs({
            ...menu,
            closable: menu.key !== ''
          })
        )
      }
    }
  }, [dispatch, location.pathname, Menus])

  // 监听路由变化
  useEffect(() => {
    navigate(activeTagId)
    dispatch(setSelectedKeys(activeTagId))
  }, [activeTagId, dispatch, navigate])

  return (
    <div>
      <Tabs
        tabBarStyle={{ margin: 0 }} // tab bar 的样式对象
        onChange={onChange} //切换面板的回调
        activeKey={activeTagId} //当前激活 tab 面板的 key
        type="editable-card" //页签的基本样式，可选 line、card、editable-card 类型
        hideAdd //是否隐藏加号图标，在 type="editable-card" 时有效
        onEdit={(targetKey, action) =>
          action === 'remove' && onClose(targetKey as string)
        } //新增和删除页签的回调，在 type="editable-card" 时有效
        //tabBarExtraContent={<TagsViewAction />} //tab bar 上额外的元素
        items={tags.map((tag) => {
          //配置选项卡内容
          return {
            key: tag.key,
            closable: tag?.closable,
            label: tag.label[definedLocale]
          }
        })}
      />
    </div>
  )
}
